3 * This is the SQLite database abstraction layer.
4 * See maintenance/sqlite/README for development notes and other specific information
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 namespace Wikimedia\Rdbms
;
30 use InvalidArgumentException
;
37 class DatabaseSqlite
extends Database
{
38 /** @var bool Whether full text is enabled */
39 private static $fulltextEnabled = null;
41 /** @var string Directory */
43 /** @var string File name for SQLite database file */
45 /** @var string Transaction mode */
48 /** @var int The number of rows affected as an integer */
49 protected $lastAffectedRowCount;
51 protected $lastResultHandle;
56 /** @var FSLockManager (hopefully on the same server as the DB) */
59 /** @var array List of shared database already attached to this connection */
60 private $alreadyAttached = [];
63 * Additional params include:
64 * - dbDirectory : directory containing the DB and the lock file directory
65 * [defaults to $wgSQLiteDataDir]
66 * - dbFilePath : use this to force the path of the DB file
67 * - trxMode : one of (deferred, immediate, exclusive)
70 function __construct( array $p ) {
71 if ( isset( $p['dbFilePath'] ) ) {
72 $this->dbPath
= $p['dbFilePath'];
73 $lockDomain = md5( $this->dbPath
);
74 // Use "X" for things like X.sqlite and ":memory:" for RAM-only DBs
75 if ( !isset( $p['dbname'] ) ||
!strlen( $p['dbname'] ) ) {
76 $p['dbname'] = preg_replace( '/\.sqlite\d?$/', '', basename( $this->dbPath
) );
78 } elseif ( isset( $p['dbDirectory'] ) ) {
79 $this->dbDir
= $p['dbDirectory'];
80 $lockDomain = $p['dbname'];
82 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
85 $this->trxMode
= isset( $p['trxMode'] ) ?
strtoupper( $p['trxMode'] ) : null;
86 if ( $this->trxMode
&&
87 !in_array( $this->trxMode
, [ 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' ] )
89 $this->trxMode
= null;
90 $this->queryLogger
->warning( "Invalid SQLite transaction mode provided." );
93 $this->lockMgr
= new FSLockManager( [
94 'domain' => $lockDomain,
95 'lockDirectory' => "{$this->dbDir}/locks"
98 parent
::__construct( $p );
101 protected static function getAttributes() {
102 return [ self
::ATTR_DB_LEVEL_LOCKING
=> true ];
106 * @param string $filename
107 * @param array $p Options map; supports:
108 * - flags : (same as __construct counterpart)
109 * - trxMode : (same as __construct counterpart)
110 * - dbDirectory : (same as __construct counterpart)
111 * @return DatabaseSqlite
114 public static function newStandaloneInstance( $filename, array $p = [] ) {
115 $p['dbFilePath'] = $filename;
117 $p['tablePrefix'] = '';
118 /** @var DatabaseSqlite $db */
119 $db = Database
::factory( 'sqlite', $p );
124 protected function doInitConnection() {
125 if ( $this->dbPath
!== null ) {
126 // Standalone .sqlite file mode.
129 $this->connectionParams
['dbname'],
130 $this->connectionParams
['tablePrefix']
132 } elseif ( $this->dbDir
!== null ) {
133 // Stock wiki mode using standard file names per DB
134 if ( strlen( $this->connectionParams
['dbname'] ) ) {
136 $this->connectionParams
['host'],
137 $this->connectionParams
['user'],
138 $this->connectionParams
['password'],
139 $this->connectionParams
['dbname'],
140 $this->connectionParams
['schema'],
141 $this->connectionParams
['tablePrefix']
144 // Caller will manually call open() later?
145 $this->connLogger
->debug( __METHOD__
. ': no database opened.' );
148 throw new InvalidArgumentException( "Need 'dbDirectory' or 'dbFilePath' parameter." );
160 * @todo Check if it should be true like parent class
164 function implicitGroupby() {
168 protected function open( $server, $user, $pass, $dbName, $schema, $tablePrefix ) {
170 $fileName = self
::generateFileName( $this->dbDir
, $dbName );
171 if ( !is_readable( $fileName ) ) {
173 throw new DBConnectionError( $this, "SQLite database not accessible" );
175 // Only $dbName is used, the other parameters are irrelevant for SQLite databases
176 $this->openFile( $fileName, $dbName, $tablePrefix );
178 return (bool)$this->conn
;
182 * Opens a database file
184 * @param string $fileName
185 * @param string $dbName
186 * @param string $tablePrefix
187 * @throws DBConnectionError
188 * @return PDO|bool SQL connection or false if failed
190 protected function openFile( $fileName, $dbName, $tablePrefix ) {
193 $this->dbPath
= $fileName;
195 if ( $this->flags
& self
::DBO_PERSISTENT
) {
196 $this->conn
= new PDO( "sqlite:$fileName", '', '',
197 [ PDO
::ATTR_PERSISTENT
=> true ] );
199 $this->conn
= new PDO( "sqlite:$fileName", '', '' );
201 } catch ( PDOException
$e ) {
202 $err = $e->getMessage();
205 if ( !$this->conn
) {
206 $this->queryLogger
->debug( "DB connection error: $err\n" );
207 throw new DBConnectionError( $this, $err );
210 $this->opened
= is_object( $this->conn
);
211 if ( $this->opened
) {
212 $this->currentDomain
= new DatabaseDomain( $dbName, null, $tablePrefix );
213 # Set error codes only, don't raise exceptions
214 $this->conn
->setAttribute( PDO
::ATTR_ERRMODE
, PDO
::ERRMODE_SILENT
);
215 # Enforce LIKE to be case sensitive, just like MySQL
216 $this->query( 'PRAGMA case_sensitive_like = 1' );
225 * @return string SQLite DB file path
228 public function getDbFilePath() {
229 return $this->dbPath
;
233 * Does not actually close the connection, just destroys the reference for GC to do its work
236 protected function closeConnection() {
243 * Generates a database file name. Explicitly public for installer.
244 * @param string $dir Directory where database resides
245 * @param string $dbName Database name
248 public static function generateFileName( $dir, $dbName ) {
249 return "$dir/$dbName.sqlite";
253 * Check if the searchindext table is FTS enabled.
254 * @return bool False if not enabled.
256 function checkForEnabledSearch() {
257 if ( self
::$fulltextEnabled === null ) {
258 self
::$fulltextEnabled = false;
259 $table = $this->tableName( 'searchindex' );
260 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name = '$table'", __METHOD__
);
262 $row = $res->fetchRow();
263 self
::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
267 return self
::$fulltextEnabled;
271 * Returns version of currently supported SQLite fulltext search module or false if none present.
274 static function getFulltextSearchModule() {
275 static $cachedResult = null;
276 if ( $cachedResult !== null ) {
277 return $cachedResult;
279 $cachedResult = false;
280 $table = 'dummy_search_test';
282 $db = self
::newStandaloneInstance( ':memory:' );
283 if ( $db->query( "CREATE VIRTUAL TABLE $table USING FTS3(dummy_field)", __METHOD__
, true ) ) {
284 $cachedResult = 'FTS3';
288 return $cachedResult;
292 * Attaches external database to our connection, see https://sqlite.org/lang_attach.html
295 * @param string $name Database name to be used in queries like
296 * SELECT foo FROM dbname.table
297 * @param bool|string $file Database file name. If omitted, will be generated
298 * using $name and configured data directory
299 * @param string $fname Calling function name
300 * @return ResultWrapper
302 function attachDatabase( $name, $file = false, $fname = __METHOD__
) {
304 $file = self
::generateFileName( $this->dbDir
, $name );
306 $file = $this->addQuotes( $file );
308 return $this->query( "ATTACH DATABASE $file AS $name", $fname );
311 protected function isWriteQuery( $sql ) {
312 return parent
::isWriteQuery( $sql ) && !preg_match( '/^(ATTACH|PRAGMA)\b/i', $sql );
315 protected function isTransactableQuery( $sql ) {
316 return parent
::isTransactableQuery( $sql ) && !in_array(
317 $this->getQueryVerb( $sql ),
318 [ 'ATTACH', 'PRAGMA' ],
324 * SQLite doesn't allow buffered results or data seeking etc, so we'll use fetchAll as the result
327 * @return bool|ResultWrapper
329 protected function doQuery( $sql ) {
330 $res = $this->getBindingHandle()->query( $sql );
331 if ( $res === false ) {
335 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
336 $this->lastAffectedRowCount
= $r->rowCount();
337 $res = new ResultWrapper( $this, $r->fetchAll() );
343 * @param ResultWrapper|mixed $res
345 function freeResult( $res ) {
346 if ( $res instanceof ResultWrapper
) {
354 * @param ResultWrapper|array $res
355 * @return stdClass|bool
357 function fetchObject( $res ) {
358 if ( $res instanceof ResultWrapper
) {
364 $cur = current( $r );
365 if ( is_array( $cur ) ) {
368 foreach ( $cur as $k => $v ) {
369 if ( !is_numeric( $k ) ) {
381 * @param ResultWrapper|mixed $res
384 function fetchRow( $res ) {
385 if ( $res instanceof ResultWrapper
) {
390 $cur = current( $r );
391 if ( is_array( $cur ) ) {
401 * The PDO::Statement class implements the array interface so count() will work
403 * @param ResultWrapper|array|false $res
406 function numRows( $res ) {
407 // false does not implement Countable
408 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
410 return is_array( $r ) ?
count( $r ) : 0;
414 * @param ResultWrapper $res
417 function numFields( $res ) {
418 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
419 if ( is_array( $r ) && count( $r ) > 0 ) {
420 // The size of the result array is twice the number of fields. (T67578)
421 return count( $r[0] ) / 2;
423 // If the result is empty return 0
429 * @param ResultWrapper $res
433 function fieldName( $res, $n ) {
434 $r = $res instanceof ResultWrapper ?
$res->result
: $res;
435 if ( is_array( $r ) ) {
436 $keys = array_keys( $r[0] );
445 * Use MySQL's naming (accounts for prefix etc) but remove surrounding backticks
447 * @param string $name
448 * @param string $format
451 function tableName( $name, $format = 'quoted' ) {
452 // table names starting with sqlite_ are reserved
453 if ( strpos( $name, 'sqlite_' ) === 0 ) {
457 return str_replace( '"', '', parent
::tableName( $name, $format ) );
461 * This must be called after nextSequenceVal
465 function insertId() {
466 // PDO::lastInsertId yields a string :(
467 return intval( $this->getBindingHandle()->lastInsertId() );
471 * @param ResultWrapper|array $res
474 function dataSeek( $res, $row ) {
475 if ( $res instanceof ResultWrapper
) {
482 for ( $i = 0; $i < $row; $i++
) {
491 function lastError() {
492 if ( !is_object( $this->conn
) ) {
493 return "Cannot return last error, no db connection";
495 $e = $this->conn
->errorInfo();
503 function lastErrno() {
504 if ( !is_object( $this->conn
) ) {
505 return "Cannot return last error, no db connection";
507 $info = $this->conn
->errorInfo();
516 protected function fetchAffectedRowCount() {
517 return $this->lastAffectedRowCount
;
520 function tableExists( $table, $fname = __METHOD__
) {
521 $tableRaw = $this->tableName( $table, 'raw' );
522 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
523 return true; // already known to exist
526 $encTable = $this->addQuotes( $tableRaw );
528 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=$encTable" );
530 return $res->numRows() ?
true : false;
534 * Returns information about an index
535 * Returns false if the index does not exist
536 * - if errors are explicitly ignored, returns NULL on failure
538 * @param string $table
539 * @param string $index
540 * @param string $fname
541 * @return array|false
543 function indexInfo( $table, $index, $fname = __METHOD__
) {
544 $sql = 'PRAGMA index_info(' . $this->addQuotes( $this->indexName( $index ) ) . ')';
545 $res = $this->query( $sql, $fname );
546 if ( !$res ||
$res->numRows() == 0 ) {
550 foreach ( $res as $row ) {
551 $info[] = $row->name
;
558 * @param string $table
559 * @param string $index
560 * @param string $fname
563 function indexUnique( $table, $index, $fname = __METHOD__
) {
564 $row = $this->selectRow( 'sqlite_master', '*',
567 'name' => $this->indexName( $index ),
569 if ( !$row ||
!isset( $row->sql
) ) {
573 // $row->sql will be of the form CREATE [UNIQUE] INDEX ...
574 $indexPos = strpos( $row->sql
, 'INDEX' );
575 if ( $indexPos === false ) {
578 $firstPart = substr( $row->sql
, 0, $indexPos );
579 $options = explode( ' ', $firstPart );
581 return in_array( 'UNIQUE', $options );
585 * Filter the options used in SELECT statements
587 * @param array $options
590 function makeSelectOptions( $options ) {
591 foreach ( $options as $k => $v ) {
592 if ( is_numeric( $k ) && ( $v == 'FOR UPDATE' ||
$v == 'LOCK IN SHARE MODE' ) ) {
597 return parent
::makeSelectOptions( $options );
601 * @param array $options
604 protected function makeUpdateOptionsArray( $options ) {
605 $options = parent
::makeUpdateOptionsArray( $options );
606 $options = self
::fixIgnore( $options );
612 * @param array $options
615 static function fixIgnore( $options ) {
616 # SQLite uses OR IGNORE not just IGNORE
617 foreach ( $options as $k => $v ) {
618 if ( $v == 'IGNORE' ) {
619 $options[$k] = 'OR IGNORE';
627 * @param array $options
630 function makeInsertOptions( $options ) {
631 $options = self
::fixIgnore( $options );
633 return parent
::makeInsertOptions( $options );
637 * Based on generic method (parent) with some prior SQLite-sepcific adjustments
638 * @param string $table
640 * @param string $fname
641 * @param array $options
644 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
645 if ( !count( $a ) ) {
649 # SQLite can't handle multi-row inserts, so divide up into multiple single-row inserts
650 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
652 foreach ( $a as $v ) {
653 if ( !parent
::insert( $table, $v, "$fname/multi-row", $options ) ) {
658 $ret = parent
::insert( $table, $a, "$fname/single-row", $options );
665 * @param string $table
666 * @param array $uniqueIndexes Unused
667 * @param string|array $rows
668 * @param string $fname
669 * @return bool|ResultWrapper
671 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
672 if ( !count( $rows ) ) {
676 # SQLite can't handle multi-row replaces, so divide up into multiple single-row queries
677 if ( isset( $rows[0] ) && is_array( $rows[0] ) ) {
679 foreach ( $rows as $v ) {
680 if ( !$this->nativeReplace( $table, $v, "$fname/multi-row" ) ) {
685 $ret = $this->nativeReplace( $table, $rows, "$fname/single-row" );
692 * Returns the size of a text field, or -1 for "unlimited"
693 * In SQLite this is SQLITE_MAX_LENGTH, by default 1GB. No way to query it though.
695 * @param string $table
696 * @param string $field
699 function textFieldSize( $table, $field ) {
706 function unionSupportsOrderAndLimit() {
711 * @param string[] $sqls
712 * @param bool $all Whether to "UNION ALL" or not
715 function unionQueries( $sqls, $all ) {
716 $glue = $all ?
' UNION ALL ' : ' UNION ';
718 return implode( $glue, $sqls );
724 function wasDeadlock() {
725 return $this->lastErrno() == 5; // SQLITE_BUSY
731 function wasReadOnlyError() {
732 return $this->lastErrno() == 8; // SQLITE_READONLY;
735 public function wasConnectionError( $errno ) {
736 return $errno == 17; // SQLITE_SCHEMA;
739 protected function wasKnownStatementRollbackError() {
740 // ON CONFLICT ROLLBACK clauses make it so that SQLITE_CONSTRAINT error is
741 // ambiguous with regard to whether it implies a ROLLBACK or an ABORT happened.
742 // https://sqlite.org/lang_createtable.html#uniqueconst
743 // https://sqlite.org/lang_conflict.html
748 * @return string Wikitext of a link to the server software's web site
750 public function getSoftwareLink() {
751 return "[{{int:version-db-sqlite-url}} SQLite]";
755 * @return string Version information from the database
757 function getServerVersion() {
758 $ver = $this->getBindingHandle()->getAttribute( PDO
::ATTR_SERVER_VERSION
);
764 * Get information about a given field
765 * Returns false if the field does not exist.
767 * @param string $table
768 * @param string $field
769 * @return SQLiteField|bool False on failure
771 function fieldInfo( $table, $field ) {
772 $tableName = $this->tableName( $table );
773 $sql = 'PRAGMA table_info(' . $this->addQuotes( $tableName ) . ')';
774 $res = $this->query( $sql, __METHOD__
);
775 foreach ( $res as $row ) {
776 if ( $row->name
== $field ) {
777 return new SQLiteField( $row, $tableName );
784 protected function doBegin( $fname = '' ) {
785 if ( $this->trxMode
) {
786 $this->query( "BEGIN {$this->trxMode}", $fname );
788 $this->query( 'BEGIN', $fname );
797 function strencode( $s ) {
798 return substr( $this->addQuotes( $s ), 1, -1 );
805 function encodeBlob( $b ) {
806 return new Blob( $b );
810 * @param Blob|string $b
813 function decodeBlob( $b ) {
814 if ( $b instanceof Blob
) {
822 * @param string|int|null|bool|Blob $s
825 function addQuotes( $s ) {
826 if ( $s instanceof Blob
) {
827 return "x'" . bin2hex( $s->fetch() ) . "'";
828 } elseif ( is_bool( $s ) ) {
830 } elseif ( strpos( (string)$s, "\0" ) !== false ) {
831 // SQLite doesn't support \0 in strings, so use the hex representation as a workaround.
832 // This is a known limitation of SQLite's mprintf function which PDO
833 // should work around, but doesn't. I have reported this to php.net as bug #63419:
834 // https://bugs.php.net/bug.php?id=63419
835 // There was already a similar report for SQLite3::escapeString, bug #62361:
836 // https://bugs.php.net/bug.php?id=62361
837 // There is an additional bug regarding sorting this data after insert
838 // on older versions of sqlite shipped with ubuntu 12.04
839 // https://phabricator.wikimedia.org/T74367
840 $this->queryLogger
->debug(
842 ': Quoting value containing null byte. ' .
843 'For consistency all binary data should have been ' .
844 'first processed with self::encodeBlob()'
846 return "x'" . bin2hex( (string)$s ) . "'";
848 return $this->getBindingHandle()->quote( (string)$s );
852 public function buildSubstring( $input, $startPosition, $length = null ) {
853 $this->assertBuildSubstringParams( $startPosition, $length );
854 $params = [ $input, $startPosition ];
855 if ( $length !== null ) {
858 return 'SUBSTR(' . implode( ',', $params ) . ')';
862 * @param string $field Field or column to cast
866 public function buildStringCast( $field ) {
867 return 'CAST ( ' . $field . ' AS TEXT )';
871 * No-op version of deadlockLoop
875 public function deadlockLoop( /*...*/ ) {
876 $args = func_get_args();
877 $function = array_shift( $args );
879 return $function( ...$args );
886 protected function replaceVars( $s ) {
887 $s = parent
::replaceVars( $s );
888 if ( preg_match( '/^\s*(CREATE|ALTER) TABLE/i', $s ) ) {
889 // CREATE TABLE hacks to allow schema file sharing with MySQL
891 // binary/varbinary column type -> blob
892 $s = preg_replace( '/\b(var)?binary(\(\d+\))/i', 'BLOB', $s );
893 // no such thing as unsigned
894 $s = preg_replace( '/\b(un)?signed\b/i', '', $s );
896 $s = preg_replace( '/\b(tiny|small|medium|big|)int(\s*\(\s*\d+\s*\)|\b)/i', 'INTEGER', $s );
897 // floating point types -> REAL
899 '/\b(float|double(\s+precision)?)(\s*\(\s*\d+\s*(,\s*\d+\s*)?\)|\b)/i',
904 $s = preg_replace( '/\b(var)?char\s*\(.*?\)/i', 'TEXT', $s );
905 // TEXT normalization
906 $s = preg_replace( '/\b(tiny|medium|long)text\b/i', 'TEXT', $s );
907 // BLOB normalization
908 $s = preg_replace( '/\b(tiny|small|medium|long|)blob\b/i', 'BLOB', $s );
910 $s = preg_replace( '/\bbool(ean)?\b/i', 'INTEGER', $s );
912 $s = preg_replace( '/\b(datetime|timestamp)\b/i', 'TEXT', $s );
914 $s = preg_replace( '/\benum\s*\([^)]*\)/i', 'TEXT', $s );
915 // binary collation type -> nothing
916 $s = preg_replace( '/\bbinary\b/i', '', $s );
917 // auto_increment -> autoincrement
918 $s = preg_replace( '/\bauto_increment\b/i', 'AUTOINCREMENT', $s );
919 // No explicit options
920 $s = preg_replace( '/\)[^);]*(;?)\s*$/', ')\1', $s );
921 // AUTOINCREMENT should immedidately follow PRIMARY KEY
922 $s = preg_replace( '/primary key (.*?) autoincrement/i', 'PRIMARY KEY AUTOINCREMENT $1', $s );
923 } elseif ( preg_match( '/^\s*CREATE (\s*(?:UNIQUE|FULLTEXT)\s+)?INDEX/i', $s ) ) {
924 // No truncated indexes
925 $s = preg_replace( '/\(\d+\)/', '', $s );
927 $s = preg_replace( '/\bfulltext\b/i', '', $s );
928 } elseif ( preg_match( '/^\s*DROP INDEX/i', $s ) ) {
929 // DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
930 $s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
931 } elseif ( preg_match( '/^\s*INSERT IGNORE\b/i', $s ) ) {
932 // INSERT IGNORE --> INSERT OR IGNORE
933 $s = preg_replace( '/^\s*INSERT IGNORE\b/i', 'INSERT OR IGNORE', $s );
939 public function lock( $lockName, $method, $timeout = 5 ) {
940 if ( !is_dir( "{$this->dbDir}/locks" ) ) { // create dir as needed
941 if ( !is_writable( $this->dbDir
) ||
!mkdir( "{$this->dbDir}/locks" ) ) {
942 throw new DBError( $this, "Cannot create directory \"{$this->dbDir}/locks\"." );
946 return $this->lockMgr
->lock( [ $lockName ], LockManager
::LOCK_EX
, $timeout )->isOK();
949 public function unlock( $lockName, $method ) {
950 return $this->lockMgr
->unlock( [ $lockName ], LockManager
::LOCK_EX
)->isOK();
954 * Build a concatenation list to feed into a SQL query
956 * @param string[] $stringList
959 function buildConcat( $stringList ) {
960 return '(' . implode( ') || (', $stringList ) . ')';
963 public function buildGroupConcatField(
964 $delim, $table, $field, $conds = '', $join_conds = []
966 $fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
968 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
972 * @param string $oldName
973 * @param string $newName
974 * @param bool $temporary
975 * @param string $fname
976 * @return bool|ResultWrapper
977 * @throws RuntimeException
979 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
980 $res = $this->query( "SELECT sql FROM sqlite_master WHERE tbl_name=" .
981 $this->addQuotes( $oldName ) . " AND type='table'", $fname );
982 $obj = $this->fetchObject( $res );
984 throw new RuntimeException( "Couldn't retrieve structure for table $oldName" );
989 preg_quote( trim( $this->addIdentifierQuotes( $oldName ), '"' ), '/' ) .
991 $this->addIdentifierQuotes( $newName ),
996 if ( preg_match( '/^\\s*CREATE\\s+VIRTUAL\\s+TABLE\b/i', $sql ) ) {
997 $this->queryLogger
->debug(
998 "Table $oldName is virtual, can't create a temporary duplicate.\n" );
1000 $sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
1004 $res = $this->query( $sql, $fname );
1006 // Take over indexes
1007 $indexList = $this->query( 'PRAGMA INDEX_LIST(' . $this->addQuotes( $oldName ) . ')' );
1008 foreach ( $indexList as $index ) {
1009 if ( strpos( $index->name
, 'sqlite_autoindex' ) === 0 ) {
1013 if ( $index->unique
) {
1014 $sql = 'CREATE UNIQUE INDEX';
1016 $sql = 'CREATE INDEX';
1018 // Try to come up with a new index name, given indexes have database scope in SQLite
1019 $indexName = $newName . '_' . $index->name
;
1020 $sql .= ' ' . $indexName . ' ON ' . $newName;
1022 $indexInfo = $this->query( 'PRAGMA INDEX_INFO(' . $this->addQuotes( $index->name
) . ')' );
1024 foreach ( $indexInfo as $indexInfoRow ) {
1025 $fields[$indexInfoRow->seqno
] = $indexInfoRow->name
;
1028 $sql .= '(' . implode( ',', $fields ) . ')';
1030 $this->query( $sql );
1037 * List all tables on the database
1039 * @param string|null $prefix Only show tables with this prefix, e.g. mw_
1040 * @param string $fname Calling function name
1044 function listTables( $prefix = null, $fname = __METHOD__
) {
1045 $result = $this->select(
1053 foreach ( $result as $table ) {
1054 $vars = get_object_vars( $table );
1055 $table = array_pop( $vars );
1057 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
1058 if ( strpos( $table, 'sqlite_' ) !== 0 ) {
1059 $endArray[] = $table;
1068 * Override due to no CASCADE support
1070 * @param string $tableName
1071 * @param string $fName
1072 * @return bool|ResultWrapper
1073 * @throws DBReadOnlyError
1075 public function dropTable( $tableName, $fName = __METHOD__
) {
1076 if ( !$this->tableExists( $tableName, $fName ) ) {
1079 $sql = "DROP TABLE " . $this->tableName( $tableName );
1081 return $this->query( $sql, $fName );
1084 public function setTableAliases( array $aliases ) {
1085 parent
::setTableAliases( $aliases );
1086 foreach ( $this->tableAliases
as $params ) {
1087 if ( isset( $this->alreadyAttached
[$params['dbname']] ) ) {
1090 $this->attachDatabase( $params['dbname'] );
1091 $this->alreadyAttached
[$params['dbname']] = true;
1095 public function resetSequenceForTable( $table, $fname = __METHOD__
) {
1096 $encTable = $this->addIdentifierQuotes( 'sqlite_sequence' );
1097 $encName = $this->addQuotes( $this->tableName( $table, 'raw' ) );
1098 $this->query( "DELETE FROM $encTable WHERE name = $encName", $fname );
1101 public function databasesAreIndependent() {
1108 public function __toString() {
1109 return is_object( $this->conn
)
1110 ?
'SQLite ' . (string)$this->conn
->getAttribute( PDO
::ATTR_SERVER_VERSION
)
1111 : '(not connected)';
1117 protected function getBindingHandle() {
1118 return parent
::getBindingHandle();
1123 * @deprecated since 1.29
1125 class_alias( DatabaseSqlite
::class, 'DatabaseSqlite' );